package com.cordova.test.imageselect.view

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.util.DisplayMetrics
import android.util.Log
import android.view.*
import android.widget.PopupWindow
import android.widget.Toast
import com.cordova.test.imageselect.LoadImageResource
import com.cordova.test.imageselect.R
import com.cordova.test.imageselect.adapter.PopupAdapter
import com.cordova.test.imageselect.adapter.RecyclerViewAdapter
import com.cordova.test.imageselect.module.ImageFolder
import com.cordova.test.imageselect.module.ImageItem
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), LoadImageResource.OnImagesLoadedListener {

    /**
     * 静态对象创建
     */
    companion object {
        var EXCUTE_CAMERA = "open_camera"
        var OPEN_STORE_PREMISSION = 1
        val OPEN_CAMERA_PERMISSION = 2
        /** 根据屏幕宽度与密度计算GridView显示的列数， 最少为三列，并获取Item宽度  */
        fun getImageItemWidth(activity: Context): Int {
            val screenWidth = activity.resources.displayMetrics.widthPixels
            val densityDpi = activity.resources.displayMetrics.densityDpi
            var cols = screenWidth / densityDpi
            cols = if (cols < 3) 3 else cols
            val columnSpace = (2 * activity.resources.displayMetrics.density).toInt()
            return (screenWidth - columnSpace * (cols - 1)) / cols
        }

    }

    override fun onImagesLoaded(imageFolders: List<ImageFolder>) {
        if (imageFolders.isNotEmpty()) {
            mImageFolder = imageFolders as ArrayList<ImageFolder>
            adapter?.setImageList(imageFolders[0].images!!)
            list = imageFolders[0].images!!
        }
//        else {
//            adapter?.setImageList(null)
//        }

    }

    var recycler: RecyclerView? = null          //展示图片列表的view
    var list: ArrayList<ImageItem> = ArrayList()//存储图片的list
    var adapter: RecyclerViewAdapter? = null    //展示图片列表的view的适配器
    var mImageFolder: ArrayList<ImageFolder>? = null // 图片文件夹的集合
    var selectedImageList: ArrayList<ImageItem>? = null
    private var bottomView: View? = null
    var isShowCamera: Boolean = true


    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initData()
    }

    private fun initView() {
        toolBar()
//        isShowCamera = intent.getBooleanExtra(EXCUTE_CAMERA, false)
        adapter = RecyclerViewAdapter(this@MainActivity, isShowCamera)
        recycler = findViewById(R.id.recycler) as RecyclerView?
        recycler?.layoutManager = GridLayoutManager(this@MainActivity, 3)
        recycler?.adapter = adapter
        bottomView = findViewById(R.id.bottom)
        mImageFolder = ArrayList()
        select_folder.setOnClickListener {
            showFolderPopupWindow()
        }

    }

    private fun showFolderPopupWindow() {
//        if (mImageFolder!!.isNotEmpty()) {
        val popupWindow = PopupWindow()
        val view: View = LayoutInflater.from(this@MainActivity).inflate(R.layout.pop_layout, null, false)
        val rvPopup: RecyclerView = view.findViewById(R.id.rv_popup) as RecyclerView
        rvPopup.layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.VERTICAL, false)
        val popAdapter = PopupAdapter(this@MainActivity)
        rvPopup.adapter = popAdapter
        popAdapter.setFolderItemClickListener(object : PopupAdapter.OnFolderItemClickListener {
            override fun onItemClickListener(viewHolder: PopupAdapter.PopupViewHolder, position: Int) {
                popupWindow.dismiss()
                adapter?.setImageList(mImageFolder?.get(position)?.images)
                Log.e(MainActivity::class.java.simpleName, "position:     $position ")
            }
        })
        popAdapter.setFolderList(mImageFolder)
        popupWindow.contentView = view
        popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT  //如果不设置，就是 AnchorView 的宽度
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        popupWindow.height = displayMetrics.heightPixels * 3 / 5
//        popupWindow.height = windowManager.defaultDisplay.height * 3 / 5
        popupWindow.isFocusable = true
        popupWindow.setBackgroundDrawable(ColorDrawable(0))
        popupWindow.isOutsideTouchable = true
        popupWindow.animationStyle = R.style.MyPopupWindow_anim_style
        if (popupWindow.isShowing) {
            popupWindow.dismiss()
        }
        if (!isFinishing)
            popupWindow.showAtLocation(bottomView, Gravity.BOTTOM, 0, bottomView!!.height)
        val lp: WindowManager.LayoutParams = window.attributes
        lp.alpha = 0.3f
        window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        window.attributes = lp
        bottomView?.alpha = 1.0f
        popupWindow.setOnDismissListener {
            val layoutParams: WindowManager.LayoutParams = window.attributes
            layoutParams.alpha = 1.0f
            window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            window.attributes = layoutParams
        }
//        }
    }

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    private fun initData() {
        //判断是否有读取存储权限，没有去请求，有直接去读取图片资源
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), OPEN_STORE_PREMISSION)
//            Toast.makeText(this@MainActivity, "未获取到权限，部分功能将无法正常使用", Toast.LENGTH_SHORT).show()
        } else {
            //获取权限之后读取图片
            LoadImageResource(this@MainActivity, null, this@MainActivity)
        }
        //通过接口实现item点击事件
        adapter?.setImageClickListener(object : RecyclerViewAdapter.OnImageItemClickListener {
            override fun onItemClick(viewHolder: RecyclerView.ViewHolder, position: Int) {

                val path: String? = if (isShowCamera) {
                    if (position == 0) {
                        openCamera()
                        return
                    }
                    adapter?.getImageList()?.get(position - 1)?.path.toString()
                } else {
                    adapter?.getImageList()?.get(position)?.path.toString()
                }
                ImagePreviewActivity.start(this@MainActivity, path)
            }
        })
    }

    /**
     * toolBar 配置
     */
    private fun toolBar() {
        val toolBar: Toolbar = findViewById(R.id.img_select_toolbar) as Toolbar
        // 主标题
        toolBar.title = ""
        setSupportActionBar(toolBar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
//        supportActionBar?.setHomeButtonEnabled(true)
//        左边的小箭头（注意需要在setSupportActionBar(toolbar)之后才有效果）
        toolBar.setNavigationIcon(R.drawable.ic_arrow_back)
    }

    fun openCamera() {
        val intent = Intent()
        intent.action = MediaStore.ACTION_IMAGE_CAPTURE
        startActivityForResult(intent, 3)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == android.R.id.home) {
            this.finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    @RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (grantResults.isEmpty()) {
            return
        }
        when (requestCode) {
            OPEN_STORE_PREMISSION -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted 授予权限
                LoadImageResource(this@MainActivity, null, this@MainActivity)
            } else {
                // Permission Denied 权限被拒绝
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
                Toast.makeText(this@MainActivity, "未获取到存储权限，部分功能将无法正常使用", Toast.LENGTH_SHORT).show()
            }
            OPEN_CAMERA_PERMISSION ->
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted 授予权限

                } else {
                    // Permission Denied 权限被拒绝
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
                    Toast.makeText(this@MainActivity, "未获取到相机权限，部分功能将无法正常使用", Toast.LENGTH_SHORT).show()
                }
            else -> {
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    /**
     *横竖屏切换，后台返回等页面重新载入状态时读取之前页面消失之前存储的数据
     */
    override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        super.onRestoreInstanceState(savedInstanceState)
        if (savedInstanceState != null) {
            mImageFolder = savedInstanceState.getParcelableArrayList<ImageFolder>("imageFolder")
            list = savedInstanceState.getParcelableArrayList<ImageItem>("allImage")
//            if (mImageFolder != null  && (mImageFolder as ArrayList<ImageFolder>).size > 0) {
//                adapter?.setImageList((mImageFolder as ArrayList<ImageFolder>)[0].images)
//            }
            adapter?.setImageList(list)
        }
    }

    /**
     *页面横竖屏切换，前后台切换等操作时调用，存储数据，等页面再次创建时读取使用
     */
    override fun onSaveInstanceState(outState: Bundle?) {
        outState?.putParcelableArrayList("imageFolder", mImageFolder)
        outState?.putParcelableArrayList("allImage", list)
        super.onSaveInstanceState(outState)
    }
}
